package com.xpjhs.util;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;

import com.xpjhs.cache.UserCacheManager;
import com.xpjhs.user.model.ShiroUser;
import com.xpjhs.user.model.User;

public class ShiroUtils {

	/**
	 * 获取当前用户名
	 * @return 当前用户名
	 */
	public static String getUsername(){
		String username = null;
		Subject subject = ThreadContext.getSubject();
		if (subject!=null){
			Object principal = subject.getPrincipal();
			if (principal instanceof String){
				username = (String)principal;
			}else{
				ShiroUser shiroUser = (ShiroUser)subject.getPrincipal();
				if (shiroUser!=null){
					username = shiroUser.getUsername();
				}
			}
			
		}
		return username;
	}
	
	/**
	 * 获取当前用户基础信息
	 * @return
	 */
	public static ShiroUser getShiroUser(){
		ShiroUser shiroUser = null;
		
		Subject subject = ThreadContext.getSubject();
		if (subject!=null){
			Object principal = subject.getPrincipal();
			if (principal instanceof String){
    			String username = (String)principal;
    			User dbUser = UserCacheManager.getUser(username);
    			shiroUser  = new ShiroUser(dbUser.getUsername(), dbUser.getRealName(), dbUser.getUserIcon());
    		}else if (principal instanceof ShiroUser){
    			shiroUser =(ShiroUser)principal;
    		}

			shiroUser = (ShiroUser)subject.getPrincipal();
		}
		return shiroUser;
	}
}
